import React, { PureComponent } from 'react';
// 引入整个网页
import Index from './index';
// 引入路由
import { BrowserRouter, Route, Prompt } from 'react-router-dom';
// 引入框架
import { message, Modal, Radio } from 'antd';
// 引入axios
import Axios from 'axios';
import { webSite } from './website';
import cookie from 'react-cookies';
// 引入start 
import store from './store/index';
// 引入动作
import { ApiuserId, ApiuserQq } from './store/actionCreators/ApiCreators';
export default class isRoute extends PureComponent {
  constructor() {
    super()
    this.state = {
      // 主页音乐
      HomeMusic: [],
      // 主页音乐的下标
      HomeIndex: 0,
      visible: false,
      isAutoPlay: false,
      // 音乐地址
      httpMusci: '',
      // 单选框的value值
      value: 1,
      // 添加按钮是否显示
      AddMusci: false
    }
    // state的写法
    this.unSubscribe = store.subscribe(() => {
      // 强制更新
      this.forceUpdate()
    })
  }

  // 清除订阅者
  componentWillUnmount () {
    this.unSubscribe()
    // 卸载异步操作设置状态
    this.setState = () => {
      return;
    }
  }

  componentDidMount () {
    document.getElementsByClassName('HomeAudioKong')[0].addEventListener('touchmove', (e) => {
      e.preventDefault(); // 阻止默认事件
    }, { passive: false }); // 兼容苹果安卓
    // 获取仓库的id值
    // 获取仓库的密码值
    let { userId, userQq } = store.getState().reducer;
    // store没有时判断cookie
    if (!userId || !userQq) {
      if (cookie.load('user') !== undefined && cookie.load('userid') !== undefined) {
        Axios.create({
          baseURL: `${webSite}:3003`
        }).post("/loginCook", { username: cookie.load('user'), userid: cookie.load('userid') }).then(err => {
          if (err.data.code === 'L0001') {
            // 登录成功之后把登录信息存储到本地然后返回主页
            store.dispatch(ApiuserId(err.data.data.id));
            store.dispatch(ApiuserQq(err.data.data.qq));
          }
        })
      }
    }
  }
  // 单选框的value值
  onChange = e => {
    this.setState({
      value: e.target.value,
    }, () => {
      switch (e.target.value) {
        case 1:
          // 调用一次点击事件
          this.Ifmusic()
          break;
        case 2:
          // 调用一次抖音列表的函数
          Axios.create({
            baseURL: `${webSite}:3003`
          }).post("/MusicClass", { cla: 'douyin' }).then(err => {
            if (err.data.code === 'M0099') {
              // 请求回的数组返回给列表
              this.setState({
                HomeMusic: err.data.data,
                AddMusci: true
              })
            }
          }).catch(() => {
            message.error({ content: '网络错误', className: 'bulletChatMessage' });
          })
          break;
        default:
          break;
      }
    })
  };
  // 首页音符的点击事件
  Ifmusic = () => {
    let { userId } = store.getState().reducer;
    let { value } = this.state;
    if (userId) {
      if (value === 1) {
        // 发送请求获取登录用户的默认id
        Axios.create({
          baseURL: `${webSite}:3003`
        }).post("/lightMusic", { id: userId }).then(err => {
          if (err.data.code === 'M0001') {
            this.setState({
              // 开启弹窗
              visible: true,
              AddMusci: false
            });
          } else if (err.data.code === 'M0002') {
            this.setState({
              // 开启弹窗
              visible: true,
              AddMusci: false,
              // 获取到的数据返回给用户
              HomeMusic: err.data.data
            })
          }
        }).catch(() => {
          message.error({ content: '网络错误', className: 'bulletChatMessage' });
        })
      } else {
        // 开启弹窗
        this.setState({
          visible: true
        })
      }
    } else {
      message.info({ content: '请先登录', className: 'bulletChatMessage' })
    }
  }
  // 取消对话框
  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };

  // 上一曲
  lightPrev = () => {
    let { HomeMusic, HomeIndex } = this.state;
    // 用户没有默认音乐时不允许点击
    if (HomeMusic.length === 0) {
      message.info({ content: '请先添加歌曲或切换列表', className: 'bulletChatMessage' });
      return;
    }
    if (HomeIndex - 1 >= 0) {
      this.setState({
        HomeIndex: HomeIndex - 1
      }, () => {
        // 下标 - 1 开启音乐
        this.kaiqiPlay()
      })
    } else {
      this.setState({
        HomeIndex: HomeMusic.length - 1
      }, () => {
        // 下标为最后一个开启音乐
        this.kaiqiPlay()
      })
    }
  }
  // 下一曲
  lightNext = () => {
    let { HomeMusic, HomeIndex } = this.state;
    // 用户没有默认音乐时不允许点击
    if (HomeMusic.length === 0) {
      message.info({ content: '请先添加歌曲或切换列表', className: 'bulletChatMessage' });
      return;
    }
    if (HomeIndex < HomeMusic.length - 1) {
      this.setState({
        HomeIndex: HomeIndex + 1
      }, () => {
        // 下标 + 1 开启音乐
        this.kaiqiPlay()
      })
    } else {
      this.setState({
        HomeIndex: 0
      }, () => {
        // 重头开始 开启音乐
        this.kaiqiPlay()
      })
    }
  }
  // 开启音乐函数
  lightPlay = (blo) => {
    let { HomeMusic } = this.state;
    // 用户没有默认音乐时不允许点击
    if (HomeMusic.length === 0) {
      message.info({ content: '请先添加歌曲或切换列表', className: 'bulletChatMessage' });
      return;
    }
    // 开启关闭切换
    this.setState({
      isAutoPlay: blo
    })
    if (blo) {
      this.kaiqiPlay()
    } else {
      let audio = document.getElementById('AudioHome');
      audio.pause();
    }
  }
  // 音乐
  kaiqiPlay = () => {
    let { HomeMusic, HomeIndex } = this.state;
    if (HomeMusic[HomeIndex] !== undefined) {
      let audio = document.getElementById('AudioHome');
      audio.pause();
      Axios.create({
        baseURL: `${webSite}:3003`
      }).post("/gethttpMusci", { id: HomeMusic[HomeIndex].musicId }).then(err => {
        if (err.data.code === 'M0003') {
          this.setState({
            httpMusci: err.data.url,
            isAutoPlay: true
          }, () => {
            audio.play().catch(() => {
              message.info({ content: '资源失效', className: 'bulletChatMessage' })
            })
          })
        }
      }).catch(() => {
        message.error({ content: '网络错误', className: 'bulletChatMessage' });
      })
    }
  }
  // 音乐结束时的回调
  EndedMusic = () => {
    this.lightNext()
  }
  // 返回的class类名
  AudioHomeClass = (cla) => {
    if (cla === this.state.HomeIndex) {
      return 'HomeAudioClass_body_div HomeAudioClass_body_divActive';
    }
    return 'HomeAudioClass_body_div';
  }
  // 歌曲点击切换
  ClickAudioIndex = (index) => {
    this.setState({
      HomeIndex: index
    }, () => {
      this.kaiqiPlay()
    })
  }
  // 添加音乐的函数
  addFunM = (e, list) => {
    let { userId } = store.getState().reducer;
    e.stopPropagation();
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/AddMusic", { MusicId: userId, MusicList: list }).then(err => {
      // 用户第一次添加成功
      if (err.data.code === 'M0011') {
        message.success({ content: '添加成功', className: 'bulletChatMessage' })
      }
      // 用户好几次添加
      if (err.data.code === 'M0021') {
        message.success({ content: '添加成功', className: 'bulletChatMessage' })
      }
      // 防止用户多次添加
      if (err.data.code === 'M0031') {
        message.info({ content: '请勿重复添加', className: 'bulletChatMessage' })
      }
    }).catch(() => {
      message.error({ content: '网络错误', className: 'bulletChatMessage' });
    })
  }
  // 移动音符的函数
  HomeMusicModal = (event) => {
    // 获取小按钮
    let ba = document.getElementsByClassName('HomeAudioKong')[0];
    // 获取手机按压屏幕的x轴位置
    let touch = event.targetTouches[0];
    // // 把手指移动的距离赋值给span的left
    ba.style.left = touch.clientX - 20 + "px";
    ba.style.top = touch.clientY - 20 + "px";
  }
  render () {
    let { HomeMusic, httpMusci, AddMusci } = this.state;
    // 获取仓库的id值
    let { userId, userQq } = store.getState().reducer;
    return (
      <BrowserRouter>
        {/* 拦截器做权限判断 */}
        <Route children={() => {
          return (
            <Prompt message={location => {
              // 当用户进入生活页面时进行拦截
              if (location.pathname === '/life') {
                if (Boolean(userId) && Boolean(userQq)) {
                  return true;
                } else {
                  message.warning({ content: '请先登录才能使用生活页面功能', className: 'bulletChatMessage' });
                  return false;
                }
              }
              // 不登录不让搜索应用
              if (location.pathname === '/music') {
                if (Boolean(userId) && Boolean(userQq)) {
                  return true;
                } else {
                  message.warning({ content: '请先登录才能设置音乐', className: 'bulletChatMessage' });
                  return false;
                }
              }
              // 交友页面
              if (location.pathname === '/friend') {
                if (Boolean(userId) && Boolean(userQq)) {
                  return true;
                } else {
                  message.warning({ content: '需要先登录才能发送交友信息', className: 'bulletChatMessage' });
                  return false;
                }
              }
              // 音乐界面
              if (location.pathname === '/lightMusic') {
                if (Boolean(userId) && Boolean(userQq)) {
                  return true;
                } else {
                  message.warning({ content: '需要先登录才能使用音乐界面', className: 'bulletChatMessage' });
                  return false;
                }
              }
              // 番剧页面
              if (location.pathname === '/fanopera') {
                if (Boolean(userId) && Boolean(userQq)) {
                  return true;
                } else {
                  message.warning({ content: '需要先登录才能使用番剧', className: 'bulletChatMessage' });
                  return false;
                }
              }
              // 搜索应用页面
              if (location.pathname === '/application') {
                if (Boolean(userId) && Boolean(userQq)) {
                  return true;
                } else {
                  message.warning({ content: '您需要先登录', className: 'bulletChatMessage' });
                  return false;
                }
              }
              // 电子书页面
              if (location.pathname === '/novel') {
                if (Boolean(userId) && Boolean(userQq)) {
                  return true;
                } else {
                  message.warning({ content: '您需要先登录才能使用', className: 'bulletChatMessage' });
                  return false;
                }
              }
            }} />
          )
        }} />
        {/* 这样写主要是让主页可以使用路由方法 */}
        <Index />
        {/* 音乐播放器 */}
        <audio src={httpMusci} controls="controls" style={{ display: 'none' }} id='AudioHome' onEnded={this.EndedMusic} >
        </audio>
        {/* 音符标志 */}
        <div className='HomeAudioKong' onClick={this.Ifmusic} onTouchMove={this.HomeMusicModal}></div>
        <Modal
          visible={this.state.visible}
          onCancel={this.handleCancel}
          footer={null}
          centered={true}
          className='HomeAudioClass'
        >
          <div className='HomeAudioClass_top'>
            {/* 上一曲 */}
            <span className='player-btn btn-prev' onClick={this.lightPrev}></span>
            {/* 开启关闭按钮 */}
            {
              this.state.isAutoPlay ? <span className='player-btn btn-play btn-state-paused' onClick={() => this.lightPlay(false)}></span>
                : <span className='player-btn btn-play' onClick={() => this.lightPlay(true)}></span>
            }
            {/* 下一曲 */}
            <span className='player-btn btn-next' onClick={this.lightNext}></span>
          </div>
          {/* 歌词选项 */}
          <Radio.Group onChange={this.onChange} value={this.state.value} className='HomeAudioClass_Radio'>
            <Radio value={1}>我的收藏</Radio>
            <Radio value={2}>抖音好歌</Radio>
          </Radio.Group>
          {/* 歌曲曲目 */}
          <div className='HomeAudioClass_body'>
            {
              HomeMusic.length !== 0 ?
                HomeMusic.map((list, index) => {
                  return <div className={this.AudioHomeClass(index)} key={index} onClick={() => this.ClickAudioIndex(index)}>{list.musicUser}{
                    // 判断是否显示添加按钮
                    AddMusci ? <div className='HomeAudioClass_body_add' onClick={(e) => this.addFunM(e, list)}>添加</div> : ''
                  }</div>
                }) : <div className='HomeAudioClass_body_div'>您的收藏里还没有音乐~</div>
            }
          </div>
        </Modal>
      </BrowserRouter>
    )
  }
}
